import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
  Button,
  Card,
  Divider,
  Grid,
  Image,
  List,
  NavBar,
  Popup,
  Stepper,
  Tag,
  Toast,
  Swiper,
} from "antd-mobile";
import { LeftOutline, StarOutline, StarFill } from "antd-mobile-icons";
import detail from "../style/detail.module.css";
import imageBU from "../img/biudifou.jpg";
import left from "../img/left.png";
import home from "../img/house.png";
import ear from "../img/ear.png";
import dian from "../img/dian.png";
import { shopdetail } from "../api/detail";
import { shopping_add } from "../api/shopping";

const DetailPage = () => {
  const navigate = useNavigate();
  const [visible, setVisible] = useState(false);
  const [quantity, setQuantity] = useState(1);
  const [collected, setCollected] = useState(false);
  const [activeSpec, setActiveSpec] = useState(0);

  // 商品数据状态
  const [images, setImages] = useState<string[]>([]);
  const [productName, setProductName] = useState("");
  const [firstImage, setFirstImage] = useState("");
  const [originalPrice, setOriginalPrice] = useState("");
  const [price, setPrice] = useState("");
  const [monthSale, setMonthSale] = useState("");
  const [deliveryAddress, setDeliveryAddress] = useState("");
  const [actionType, setActionType] = useState<"add" | "buy" | null>(null);

  // 规格相关状态
  const [norm, setNorm] = useState<string[]>([]);
  const [hasSpec, setHasSpec] = useState(false);

  // 类似商品
  interface Product {
    id: number;
    img: string;
    title: string;
    price: string;
    original_price: string;
  }
  const [similarProducts, setSimilarProducts] = useState<Product[]>([]);

  // 轮播图渲染
  const items = images.map((image, index) => (
    <Swiper.Item key={index}>
      <div>
        <img className={detail.Swiper} src={image} alt="" />
      </div>
    </Swiper.Item>
  ));

  // 类似商品渲染
  const similarProduct = similarProducts.map((product, index) => (
    <div className={detail.border} key={index}>
      <Grid.Item>
        <Card bodyStyle={{ padding: 0 }} onClick={() => jump(product.id)}>
          <Image src={product.img} width="100%" />
          <div style={{ padding: "1px" }}>
            <div className={detail.productName}>{product.title}</div>
            <div className={detail.productDesc}>{product.title}</div>
            <div className={detail.productPrice}>
              <span className={detail.currentPrice}>￥{product.price}</span>
              <span className={detail.originalPrice}>
                ￥{product.original_price}
              </span>
            </div>
          </div>
        </Card>
      </Grid.Item>
    </div>
  ));

  // 规格选项渲染
  const normRender = norm.map((item, index) => (
    <div
      key={index}
      className={`${detail.specOption} ${
        activeSpec === index ? detail.activeSpec : ""
      }`}
      onClick={() => setActiveSpec(index)}
    >
      {item}
    </div>
  ));

  // 跳转到商品详情
  const jump = (id: string | number) => {
    localStorage.setItem("productId", id.toString());
    navigate("/detail");
  };

  // 获取商品详情
  useEffect(() => {
    const user = JSON.parse(localStorage.getItem("user") || "null");
    const storedId = localStorage.getItem("productId");
    // ===============商品详情接口================
    shopdetail({
      id: storedId,
      uid: user?.data?.id,
    })
      .then((res) => {
        const data = res.data.data;

        // 处理图片数据
        const imgArray = data.imgs.split(",");
        setImages(imgArray);
        setFirstImage(imgArray[0]);

        // 设置商品基本信息
        setProductName(data.title);
        setOriginalPrice(data.original_price);
        setPrice(data.price);
        setMonthSale(data.sold);
        setDeliveryAddress(data.shipping_address);
        setSimilarProducts(data.list || []);

        // 处理规格数据
        if (data.norm && Array.isArray(data.norm)) {
          // 处理字符串数组格式的规格
          if (typeof data.norm[0] === "string") {
            setNorm(data.norm);
            setHasSpec(data.norm.length > 0);
          }
          // 处理对象数组格式的规格
          else if (data.norm[0]?.value) {
            setNorm(data.norm[0].value);
            setHasSpec(data.norm[0].value.length > 0);
          }
        } else {
          // 没有规格数据时设为空数组
          setNorm([]);
          setHasSpec(false);
        }
      })
      .catch((error) => {
        console.error("获取商品详情失败:", error);
        Toast.show({
          content: "获取商品信息失败，请稍后再试",
          icon: "fail",
        });
      });
  }, []);

  // 加入购物车
  // 修改加入购物车和立即购买中的规格参数处理部分

  // 加入购物车函数修改
  const addToCart = () => {
    const user = JSON.parse(localStorage.getItem("user") || "null");
    const storedId = localStorage.getItem("productId");

    if (!user) {
      Toast.show({
        content: "请先登录",
        icon: "fail",
      });
      navigate("/login");
      return;
    }

    // 构建规格参数 - 修改为接口需要的格式
    // 正确的格式应该是这样的数组，包含name和value属性的对象
    const specValue =
      hasSpec && norm.length > 0
        ? [{ name: "规格", value: norm[activeSpec] }]
        : undefined;

    console.log("规格参数:", JSON.stringify(specValue));
    //============ 加入购物车接口================
    shopping_add({
      uid: user?.data?.id,
      id: storedId,
      num: quantity,
      norm: JSON.stringify(specValue)
    })
      .then((res) => {
        console.log("加入购物车成功！", res.data);
        if (!res.data || res.data.code !== 1) {
          throw new Error(res.data?.message || "加入购物车失败");
        }
        Toast.show({
          content: "已加入购物车",
          icon: "success",
        });

        // 存储当前商品信息用于购物车页面展示
        const productToBuy = {
          id: storedId,
          name: productName,
          price: price,
          originalPrice: originalPrice,
          image: firstImage,
          norm: specValue ? specValue[0].value : null, // 存储实际值
          quantity: quantity,
          deliveryAddress: deliveryAddress,
          selectedTime: new Date().toISOString(),
        };
        localStorage.setItem("currentPurchase", JSON.stringify(productToBuy));
        console.log("当前商品信息存储成功！", productToBuy);
        setVisible(false);
        navigate("/shopcart");
      })
      .catch((error) => {
        console.error("加入购物车失败:", error);
        Toast.show({
          content: error.response?.data?.message || "加入购物车失败",
          icon: "fail",
        });
      });
  };

  // 立即购买函数修改
  const buyNow = () => {
    if (quantity < 1) {
      Toast.show({
        content: "请至少购买一件商品！",
        icon: "error",
      });
      return;
    }

    const user = JSON.parse(localStorage.getItem("user") || "null");
    if (!user) {
      Toast.show({
        content: "请先登录",
        icon: "fail",
      });
      navigate("/login");
      return;
    }

    // 构建规格参数 - 修改为接口需要的格式
    const specValue =
      hasSpec && norm.length > 0
        ? [{ name: "规格", value: norm[activeSpec] }]
        : undefined;

    console.log("规格参数:", JSON.stringify(specValue));
    // 存储商品信息用于立即购买页面
    const productToBuy = {
      id: localStorage.getItem("productId"),
      name: productName,
      price: price,
      originalPrice: originalPrice,
      image: firstImage,
      norm: [{ name: "规格", value: "高三" }], // 存储实际值
      quantity: quantity,
      deliveryAddress: deliveryAddress,
      selectedTime: new Date().toISOString(),
    };

    localStorage.setItem("currentPurchase", JSON.stringify(productToBuy));
    setVisible(false);
    navigate("/buynow");
  };

  // 收藏/取消收藏
  const toggleCollect = () => {
    const user = JSON.parse(localStorage.getItem("user") || "null");
    if (!user) {
      Toast.show({
        content: "请先登录",
        icon: "fail",
      });
      navigate("/login");
      return;
    }

    setCollected(!collected);
    Toast.show({
      content: collected ? "已取消收藏" : "收藏成功",
      duration: 1000,
    });
  };

  return (
    <div className={detail.container}>
      <div className={detail.header} onClick={() => navigate(-1)}>
        <img src={left} alt="" />
      </div>

      {/* 商品图片轮播 */}
      <div className={detail.imageGallery}>
        <Swiper loop autoplay>
          {items}
        </Swiper>
      </div>

      {/* 商品基本信息 */}
      <div className={detail.productInfo}>
        <b style={{ fontSize: "20px" }}>{productName}</b>
        <div className={detail.priceSection}>
          <span
            style={{ fontSize: "28px", color: "rgba(248, 125, 0, 1)" }}
            className={detail.currentPrice}
          >
            ￥{price}
          </span>
          <div className={detail.PriginalPrice}>
            原价：
            <span className={detail.originalPrice}>￥{originalPrice}</span>
          </div>
        </div>
        <div className={detail.deliveryInfo}>
          <span>快递: 包邮</span>
          <span className={detail.sales}>月销{monthSale}</span>
          <span>{deliveryAddress}</span>
        </div>
      </div>

      {/* 促销信息 */}
      <div className={detail.promotionSection}>
        <div className={detail.promotionTitle}>
          <div className={detail.promotionItem}>
            <span className={detail.detail}>每人限购10件</span>
          </div>
          <div className={detail.promotionItem}>
            <span className={detail.detail}>
              满78元享包邮,不包邮地区；新疆，西藏，台湾
            </span>
          </div>
        </div>
        <div className={detail.dian}>
          <img src={dian} alt="" />
        </div>
      </div>

      {/* 保障信息 */}
      <div className={detail.guaranteeSection}>
        <Grid style={{ display: "flex" }} columns={0} gap={0}>
          <Grid.Item>
            <div className={detail.guaranteeItem}>正品保证·</div>
          </Grid.Item>
          <Grid.Item>
            <div className={detail.guaranteeItem}>破损保障·</div>
          </Grid.Item>
          <Grid.Item>
            <div className={detail.guaranteeItem}>赠运费险·</div>
          </Grid.Item>
          <Grid.Item>
            <div className={detail.guaranteeItem}>极速退款·</div>
          </Grid.Item>
          <Grid.Item>
            <div className={detail.guaranteeItem}>七天退换</div>
          </Grid.Item>
        </Grid>
        <div className={detail.dian}>
          <img src={dian} alt="" />
        </div>
      </div>

      {/* 商品详情 */}
      <div className={detail.detailSection}>
        <b className={detail.detailTitle}>
          <div className={detail.shopcolor}>产品参数</div>
          <div className={detail.dian}>
            <img src={dian} alt="" />
          </div>
        </b>
        <b className={detail.detailTitles}>
          <div className={detail.shopcolor}>选择 颜色分类</div>
          <div className={detail.dian}>
            <img src={dian} alt="" />
          </div>
        </b>
      </div>

      {/* 商品评价 */}
      <div className={detail.reviewSection}>
        <div className={detail.shopping}>
          <b>商品评价(7362)</b>
        </div>
        <div className={detail.nameAvar}>
          <img src={imageBU} alt="" />
          <p>刘*语</p>
        </div>
        <div className={detail.pingcontent}>
          <p>
            宝贝收到了和卖家描述的一样 质量不错
            很漂亮一直想买这样的杯子，这个蓝色的稍微有点小瑕疵，不过自己用没问题
          </p>
          <p style={{ color: "#999", marginTop: 8 }}>颜色分类: 高梦幻</p>
        </div>
      </div>

      {/* 类似商品 */}
      <div className={detail.similarSection}>
        <h3 className={detail.sectionTitle}>
          <span style={{ opacity: "0" }}>`</span>类似商品
        </h3>
        <Grid columns={2} gap={8}>
          {similarProduct}
        </Grid>
      </div>

      {/* 底部操作栏 */}
      <div className={detail.footer}>
        <div className={detail.footerIcons}>
          <div className={detail.footerIcon}>
            <Image src={ear} width={20} height={20} />
            <span>客服</span>
          </div>
          <div className={detail.footerIcon}>
            <Image src={home} width={20} height={20} />
            <span>店铺</span>
          </div>
          <div className={detail.footerIcon} onClick={toggleCollect}>
            {collected ? (
              <StarFill fontSize={20} color="#ff5000" />
            ) : (
              <StarOutline fontSize={20} />
            )}
            <span>{collected ? "已收藏" : "收藏"}</span>
          </div>
        </div>
        <div className={detail.footerButtons}>
          <Button
            shape="rounded"
            color="danger"
            onClick={() => {
              setActionType("add");
              setVisible(true);
            }}
            style={{
              flex: 1,
              fontSize: 14,
              overflowY: "hidden",
              borderRadius: "25px 0px 0px 25px",
              height: 42,
            }}
          >
            加入购物车
          </Button>
          <Button
            shape="rounded"
            color="warning"
            onClick={() => {
              setActionType("buy");
              setVisible(true);
            }}
            style={{
              flex: 1,
              fontSize: 14,
              overflowY: "hidden",
              borderRadius: "0px 25px 25px 0px",
            }}
          >
            立即购买
          </Button>
        </div>
      </div>

      {/* 商品选择弹窗 */}
      <Popup
        visible={visible}
        onClose={() => setVisible(false)}
        onMaskClick={() => setVisible(false)}
        position="bottom"
        bodyStyle={{
          borderTopLeftRadius: "8px",
          borderTopRightRadius: "8px",
        }}
      >
        <div className={detail.popupContent}>
          <div className={detail.popupHeader}>
            <Image src={firstImage} width={80} height={80} fit="cover" />
            <div className={detail.popupPriceInfo}>
              <div className={detail.popupPrice}>￥{price}</div>
              <div className={detail.popupStock}>已售: {monthSale}</div>
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: "3px",
                  marginTop: "8px",
                }}
              >
                <button
                  onClick={() => setQuantity(Math.max(1, quantity - 1))}
                  className={detail.buttonS}
                >
                  –
                </button>

                <div
                  style={{
                    fontSize: "16px",
                    minWidth: "20px",
                    textAlign: "center",
                  }}
                >
                  {quantity}
                </div>

                <button
                  onClick={() => setQuantity(Math.min(10, quantity + 1))}
                  className={detail.buttonS}
                >
                  +
                </button>
              </div>
            </div>
          </div>
          <div className={detail.popupDesc}>
            <span>优惠</span>
            <span>优惠卷抵扣-2元</span>
          </div>
          {hasSpec && (
            <div className={detail.specSection}>
              <h4>颜色分类</h4>
              <div className={detail.specOptions}>{normRender}</div>
            </div>
          )}

          <div className={detail.popupButtons}>
            {actionType === "add" && (
              <Button
                block
                color="danger"
                style={{ fontSize: "16px" }}
                onClick={addToCart}
              >
                加入购物车
              </Button>
            )}
            {actionType === "buy" && (
              <Button
                block
                color="danger"
                onClick={buyNow}
                style={{ fontSize: "16px" }}
              >
                立即支付 ￥{(Number(price) * quantity).toFixed(2)}
              </Button>
            )}
          </div>
        </div>
      </Popup>
    </div>
  );
};

export default DetailPage;
